<div class="upload-container">
    <div class="upload-preview">
        <img id="preview-image" src="{{user.avatar}}" alt="预览图片" class="preview-img">
    </div>
    <div class="upload-controls">
        <input type="file" id="image-upload" accept="image/*" style="display: none;">
        <button class="upload-btn" onclick="document.getElementById('image-upload').click()">
            选择图片
        </button>
        <button class="upload-btn submit" id="submit-upload" style="display: none;">
            确认上传
        </button>
    </div>
</div>

<style>
.upload-container {
    max-width: 300px;
    margin: 20px auto;
    text-align: center;
}

.upload-preview {
    width: 200px;
    height: 200px;
    margin: 0 auto 20px;
    border: 2px dashed #ddd;
    border-radius: 8px;
    overflow: hidden;
}

.preview-img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.upload-controls {
    display: flex;
    gap: 10px;
    justify-content: center;
}

.upload-btn {
    padding: 8px 20px;
    border: none;
    border-radius: 4px;
    background: #007bff;
    color: white;
    cursor: pointer;
    transition: background-color 0.3s;
}

.upload-btn:hover {
    background: #0056b3;
}

.upload-btn.submit {
    background: #28a745;
}

.upload-btn.submit:hover {
    background: #218838;
}
</style>

<script>
document.getElementById('image-upload').addEventListener('change', function(e) {
    const file = e.target.files[0];
    if (file) {
        const reader = new FileReader();
        reader.onload = function(e) {
            document.getElementById('preview-image').src = e.target.result;
            document.getElementById('submit-upload').style.display = 'inline-block';
        }
        reader.readAsDataURL(file);
    }
});

document.getElementById('submit-upload').addEventListener('click', function() {
    const fileInput = document.getElementById('image-upload');
    const file = fileInput.files[0];
    if (file) {
        const formData = new FormData();
        formData.append('image', file);
        formData.append('description', "大家好");
        fetch('/images/upload', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('头像上传成功！');
                document.getElementById('submit-upload').style.display = 'none';
            } else {
                alert('上传失败：' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('上传过程中发生错误');
        });
    }
});
</script>
